package com.jirong.shop.config;

import com.jirong.shop.pojo.TUser;
import com.jirong.shop.service.TUserService;
import com.jirong.shop.utils.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义用户参数
 * 对需要的接口进行连接
 * 搜下用法
 * <p>
 *
 * @author zhoubin
 * @since 1.0.0
 */
@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private TUserService userService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
//
        Class<?> clazz = parameter.getParameterType();
//        如果是user就走下面的判断，登录给了用户类型就走下面去拿redis中的cookie
        return clazz == TUser.class;

    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
////    拿到用户
//        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
//        HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
////        没拿到存进去的cookie
//        String ticket = CookieUtil.getCookieValue(request, "ticketUser");
////        System.out.println(ticket);
//        if (StringUtils.isEmpty(ticket)) {
////            转发到会首页或者重定向到首页
////            assert request != null;
////            request.getRequestDispatcher("/login.html").forward(request,response);
//            return null;
//        }
//        return userService.getUserByCookie(ticket, request, response);
        return UserContext.getUser();
    }
}